package com.company.zhishidian.thread.并发;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *    锁   乐观锁   悲观锁
 */
public class TestAtomicInteger {
    private static int i=0;

    // 基于CAS 自旋 乐观锁
    private static AtomicInteger ai = new AtomicInteger(i);
    // 创建一个公共变量的本地副本
//    ThreadLocal<Integer> tl = new ThreadLocal<Integer>(){
//        @Override
//        protected Integer initialValue() {
//            return i;
//        }
//    };
   private static ThreadLocal<Integer> tl = ThreadLocal.withInitial(()->{return i;});
    public static void main(String[] args) throws InterruptedException {
        Thread th1 = new Thread(()->{
            for (int j = 0; j < 10; j++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                synchronized (TestAtomicInteger.class){
//                i++;
                    ai.incrementAndGet();
//                }
                tl.set(tl.get()+1);

            }
        });
        Thread th2 = new Thread(()->{
            for (int j = 0; j < 10; j++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                synchronized (TestAtomicInteger.class){
//                    i++;
                ai.incrementAndGet();
//                }
                tl.set(tl.get()+1);
            }
        });
        th1.start();
        th2.start();
        th1.join();
        th2.join();
//        System.out.println(i);
//        System.out.println(ai.get());
        System.out.println(tl.get());

    }
}
